package cn.e3mall.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.pojo.EasyUIDataGridResult;
import cn.e3mall.common.utils.E3Result;
import cn.e3mall.common.utils.FileUtils;
import cn.e3mall.common.utils.IDUtils;
import cn.e3mall.common.utils.JsonUtils;
import cn.e3mall.mapper.TbItemCatMapper;
import cn.e3mall.mapper.TbItemDescMapper;
import cn.e3mall.mapper.TbItemMapper;
import cn.e3mall.mapper.TbItemParamMapper;
import cn.e3mall.pojo.TbItem;
import cn.e3mall.pojo.TbItemCat;
import cn.e3mall.pojo.TbItemDesc;
import cn.e3mall.pojo.TbItemExample;
import cn.e3mall.pojo.TbItemExample.Criteria;
import cn.e3mall.pojo.TbItemParam;
import cn.e3mall.pojo.TbItemParamExample;

/**
 * 商品管理Service
 * <p>Title: ItemServiceImpl</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.cn</p> 
 * @version 1.0
 */
@Service
public class ItemServiceImpl{

	@Autowired
	private TbItemMapper itemMapper;
	@Autowired
	private TbItemDescMapper itemDescMapper;
	@Autowired
	private TbItemParamMapper itemParamMapper;
	@Autowired
	private TbItemCatMapper itemCatMapper;
	@Autowired
	private JmsTemplate jmsTemplate;
	@Resource
	private Destination topicDestination;
	@Autowired
	private JedisClient jedisClient;
	
	@Value("${REDIS_ITEM_PRE}")
	private String REDIS_ITEM_PRE;
	@Value("${ITEM_CACHE_EXPIRE}")
	private Integer ITEM_CACHE_EXPIRE;
	
	/**
	 * 根据Id查询商品信息
	* @Title: getItemById  
	* @Description: TODO
	* @param @param itemId
	* @param @return    参数  
	* @return TbItem    返回类型  
	* @throws
	 */
	public TbItem getItemById(long itemId) {
		//查询缓存
		try {
			String json = jedisClient.get(REDIS_ITEM_PRE + ":" + itemId + ":BASE");
			if(StringUtils.isNotBlank(json)) {
				TbItem tbItem = JsonUtils.jsonToPojo(json, TbItem.class);
				return tbItem;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//缓存中没有，查询数据库
		//根据主键查询
		//TbItem tbItem = itemMapper.selectByPrimaryKey(itemId);
		TbItemExample example = new TbItemExample();
		Criteria criteria = example.createCriteria();
		//设置查询条件
		criteria.andIdEqualTo(itemId);
		//执行查询
		List<TbItem> list = itemMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			//把结果添加到缓存
			try {
				jedisClient.set(REDIS_ITEM_PRE + ":" + itemId + ":BASE", JsonUtils.objectToJson(list.get(0)));
				//设置过期时间
				jedisClient.expire(REDIS_ITEM_PRE + ":" + itemId + ":BASE", ITEM_CACHE_EXPIRE);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return list.get(0);
		}
		return null;
	}

	public TbItemDesc getItemDescById(long itemId) {
		//查询缓存
		try {
			String json = jedisClient.get(REDIS_ITEM_PRE + ":" + itemId + ":DESC");
			if(StringUtils.isNotBlank(json)) {
				TbItemDesc tbItemDesc = JsonUtils.jsonToPojo(json, TbItemDesc.class);
				return tbItemDesc;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		TbItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(itemId);
		//把结果添加到缓存
		try {
			jedisClient.set(REDIS_ITEM_PRE + ":" + itemId + ":DESC", JsonUtils.objectToJson(itemDesc));
			//设置过期时间
			jedisClient.expire(REDIS_ITEM_PRE + ":" + itemId + ":DESC", ITEM_CACHE_EXPIRE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return itemDesc;
	}
	
	/**
	 * 查询商品信息并分页
	* @Title: getItemList  
	* @Description: TODO
	* @param @param page
	* @param @param rows
	* @param @return    参数  
	* @return EasyUIDataGridResult    返回类型  
	* @throws
	 */
	public EasyUIDataGridResult getItemList(int page, int rows) {
		//设置分页信息
		PageHelper.startPage(page, rows);
		//执行查询
		TbItemExample example = new TbItemExample();
		List<TbItem> list = itemMapper.selectByExample(example);
		//创建一个返回值对象
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		result.setRows(list);
		//取分页结果
		PageInfo<TbItem> pageInfo = new PageInfo<TbItem>(list);
		//取总记录数
		long total = pageInfo.getTotal();
		result.setTotal(total);
		return result;
	}
	
	public EasyUIDataGridResult getItemSearch(String title, Date created ,Date updated,int page, int rows) {
		//设置分页信息
		PageHelper.startPage(page, rows);
		//执行查询
		TbItemExample example = new TbItemExample();
		Criteria criteria = example.createCriteria();
		criteria.andUpdatedBetween(created, updated);
		criteria.andTitleLike("%"+title+"%");
		List<TbItem> list = itemMapper.selectByExample(example);
		//创建一个返回值对象
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		result.setRows(list);
		//取分页结果
		PageInfo<TbItem> pageInfo = new PageInfo<TbItem>(list);
		//取总记录数
		long total = pageInfo.getTotal();
		result.setTotal(total);
		return result;
	}
	
	
	/**
	 * 查询商品规格并分页
	* @Title: getItemList  
	* @Description: TODO
	* @param @param page
	* @param @param rows
	* @param @return    参数  
	* @return EasyUIDataGridResult    返回类型  
	* @throws
	 */
	public EasyUIDataGridResult getItemParamList(int page, int rows) {
		//设置分页信息
		PageHelper.startPage(page, rows);
		//执行查询
		TbItemParamExample example = new TbItemParamExample();
		List<TbItemParam> list = itemParamMapper.selectByExampleWithBLOBs(example);
		//创建一个返回值对象
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		result.setRows(list);
		//取分页结果
		PageInfo<TbItemParam> pageInfo = new PageInfo<TbItemParam>(list);
		//取总记录数
		long total = pageInfo.getTotal();
		result.setTotal(total);
		return result;
	}

	/**
	 * 添加商品
	* @Title: addItem  
	* @Description: TODO
	* @param @param item
	* @param @param desc
	* @param @return    参数  
	* @return E3Result    返回类型  
	* @throws
	 */
	public E3Result addItem(TbItem item, String desc) {
		//生成商品id
		final long itemId = IDUtils.genItemId();
		//补全item的属性
		item.setId(itemId);
		//1-正常，2-下架，3-删除
		item.setStatus((byte) 1);
		item.setCreated(new Date());
		item.setUpdated(new Date());
		//向商品表插入数据
		itemMapper.insert(item);
		//创建一个商品描述表对应的pojo对象。
		TbItemDesc itemDesc = new TbItemDesc();
		//补全属性
		itemDesc.setItemId(itemId);
		itemDesc.setItemDesc(desc);
		itemDesc.setCreated(new Date());
		itemDesc.setUpdated(new Date());
		//向商品描述表插入数据
		itemDescMapper.insert(itemDesc);
		//发送商品添加消息
		jmsTemplate.send(topicDestination, new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				TextMessage textMessage = session.createTextMessage(itemId + "");
				return textMessage;
			}
		});
		
		//返回成功
		return E3Result.ok();
	}
	
	/**
	 * 删除商品，并删除商品详情以及阿里云中的图片
	* @Title: deleteItem  
	* @Description: TODO
	* @param @param itemId
	* @param @return    参数  
	* @return E3Result    返回类型  
	* @throws
	 */
	public E3Result deleteItem(final long[] itemId) {
		FileUtils fileUtils=new FileUtils();
		for(long id:itemId){
			TbItem item = itemMapper.selectByPrimaryKey(id);
			if(StringUtils.isNotBlank(item.getImage())){
				fileUtils.delList(item.getImage());
			}
			itemMapper.deleteByPrimaryKey(id);
			itemDescMapper.deleteByPrimaryKey(id);
			
		}
		//返回成功
		return E3Result.ok();
	}
	
	/**
	 * 修改状态(1-正常，2-下架，3-删除)
	* @Title: updateItemState  
	* @Description: TODO
	* @param @param itemId
	* @param @param state
	* @param @return    参数  
	* @return E3Result    返回类型  
	* @throws
	 */
	public E3Result updateItemState(final long[] itemId,int state) {
		for(long id:itemId){
			TbItem item = itemMapper.selectByPrimaryKey(id);
			item.setStatus((byte)state);
			itemMapper.updateByPrimaryKey(item);
		}
		//返回成功
		if(state!=1) {
			//发送商品添加消息
			jmsTemplate.send(topicDestination, new MessageCreator() {
				@Override
				public Message createMessage(Session session) throws JMSException {
					TextMessage textMessage = session.createTextMessage(Arrays.toString(itemId)+"-");
					return textMessage;
				}
			});
		}else {
			//发送商品添加消息
			jmsTemplate.send(topicDestination, new MessageCreator() {
				@Override
				public Message createMessage(Session session) throws JMSException {
					TextMessage textMessage = session.createTextMessage(Arrays.toString(itemId)+"+");
					return textMessage;
				}
			});
		}
		return E3Result.ok();
	}
	
	/**
	 * 查询商品详情
	* @Title: itemDescE3Result  
	* @Description: TODO
	* @param @param itemId
	* @param @return    参数  
	* @return E3Result    返回类型  
	* @throws
	 */
	public E3Result itemDescE3Result(long itemId) {
		TbItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(itemId);
		//返回成功
		return new E3Result(itemDesc);
	}
	
	/**
	 * 查询商品规格
	* @Title: itemParamE3Result  
	* @Description: TODO
	* @param @param itemId
	* @param @return    参数  
	* @return E3Result    返回类型  
	* @throws
	 */
	public E3Result itemParamE3Result(long itemId) {
		TbItemParam itemParam = itemParamMapper.selectByPrimaryKey(itemId);
		//返回成功
		return new E3Result(itemParam);
	}
	
	/**
	 * 查询商品的节点
	* @Title: itemCatE3Result  
	* @Description: TODO
	* @param @param itemId
	* @param @return    参数  
	* @return E3Result    返回类型  
	* @throws
	 */
	public E3Result itemCatE3Result(long itemId) {
		TbItemCat itemCat = itemCatMapper.selectByPrimaryKey(itemId);
		//返回成功
		return new E3Result(itemCat);
	}
	
	/**
	 * 修改
	* @Title: updateItem  
	* @Description: TODO
	* @param @param item
	* @param @param desc
	* @param @return    参数  
	* @return E3Result    返回类型  
	* @throws
	 */
	public E3Result updateItem(TbItem item, String desc) {
		final long itemId_ = item.getId();
		//查询商品详情
		TbItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(itemId_);
		//修改详情信息
		itemDesc.setItemDesc(desc);
		itemMapper.updateByPrimaryKeySelective(item);
		itemDescMapper.updateByPrimaryKeySelective(itemDesc);
		//发送商品添加消息
		jmsTemplate.send(topicDestination, new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				TextMessage textMessage = session.createTextMessage(itemId_ + "");
				return textMessage;
			}
		});
		//返回成功
		return E3Result.ok();
	}
	
}
